require "find"

##############################
#
# Usage : ruby find_logs_error.rb [WORKSPACE] [SEARCHFILE] [ERRORFILENAME]"
# 	WORKSPACE : "logs" ,default
# 	SEARCHFILE : "@dot.log",default
# 	ERRORFILENAME : "error.txt",default
#
##############################

workspace = ARGV[0]!=nil?ARGV[0]:"logs"
searchfilename = ARGV[1]!=nil?ARGV[1]:"@dot.log" 
errorfilename = ARGV[2]!=nil?ARGV[2]:"error.txt"

puts workspace
puts searchfilename

def findfiles(dir, name)
	list = []
	Find.find(dir) do |path|
		Find.prune if [".",".."].include? path
		case name
		when String
			list << path if File.basename(path) == name
		else
			raise ArgumentError
		end
	end
	list
end

manifetfiles = findfiles(workspace,searchfilename)

def contains_error_in_last_line(filepath,error_file)
	puts filepath
	line = `tail #{filepath} -n 1`
	puts line
	if line.index('error') != nil
		error_file.puts filepath
		error_file.puts line
	end
end

error_file = File.new(errorfilename,'w')

for filepath in manifetfiles
	contains_error_in_last_line(filepath,error_file) 
end

error_file.close
